//
//  PVDInverterNumberViewController.swift
//  ezyform
//
//  Created by MoennigQ on 7/4/20.
//  Copyright © 2020 Client.Solution Pty Ltd. All rights reserved.
//

import UIKit
import HandyJSON
import AVFoundation
import CoreLocation
import MBProgressHUD
import RxSwift
import RxCocoa
class JobDetailInvertersListViewController: BaseViewController {
    fileprivate lazy var disposeBag = DisposeBag()
    let customView = InvertersListView()
    var model: PVDDetailModel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.model = JobDetailModelHelper.shared.jobDetailModel
        self.view = self.customView
        self.customView.setTitleInfo(R.string.localizable.serials(JobDetailModelHelper.shared.jobDetailModel.solar_water_heater ? "Tank" : "Inverter"), subTitle: JobDetailModelHelper.shared.jobDetailModel.gwt_id )
        
        //点击扫描按钮
        self.customView.scanBtn.rx.tap.subscribe { [weak self]_ in
            self?.toAddBarcode(.auto)
        }.disposed(by: self.disposeBag)
        //点击手工增加按钮
        self.customView.addManuallyBtn.rx.tap.subscribe { [weak self]_ in
            self?.toAddBarcode(.manually)
        }.disposed(by: self.disposeBag)
        //设置左滑动显示编辑删除的action
        self.customView.invertersTableView.rx.setDelegate(self)
            .disposed(by: disposeBag)
        
        //初始化数据
        var modelList = [InstallationDetailSystemDetailForInverterModel]()
        if JobDetailModelHelper.shared.jobDetailModel.solar_water_heater {//
            _ = JobDetailModelHelper.shared.jobDetailModel.system_detail.heaters.map({
                let m = InstallationDetailSystemDetailForInverterModel()
                m.inverter_brand = $0.brand
                m.inverter_model = $0.model
                m.number_inverters = $0.number_heaters
                m.tank_flag = true
                modelList.append(m)
            })
        }else{
            modelList = JobDetailModelHelper.shared.jobDetailModel.system_detail.inverters
        }
        self.customView.modelsDataObserver.accept(modelList)
        JobDetailModelHelper.shared.pvd_inverter_serial_numbers.onNext(JobDetailModelHelper.shared.jobDetailModel.pvd_inverter_serial_numbers)
        self.customView.updateUIByJobStatus(JobDetailModelHelper.shared.jobDetailModel)
        //
        Tool().getScanLicenseAndRegularExpression()
    }
    //MARK: - 扫描或手动增加barcode
    func toAddBarcode(_ addMode: ScanAddMethodMode){
        AVCaptureDevice.requestAccess(for: AVMediaType.video) { (status) in
            DispatchQueue.main.sync {
                if status {
                    let vc = ScanBarcodeViewController()
                    vc.scanningType = (JobDetailModelHelper.shared.jobDetailModel.solar_water_heater ? .tank : .inverter)
                    vc.scanAddMethodMode = addMode
                    
                    vc.modalPresentationStyle = .overFullScreen
                    self.present(vc, animated: true, completion: nil)
                }else{
                    Tool().showAlertViewWithOneBtn(message: NSLocalizedString("camera.permission", comment: ""))
                }
            }
        }
    }
    func editInverterNumber(_ index: Int){
        let editVC = EditBarcodeViewController()
        editVC.scanningType = (JobDetailModelHelper.shared.jobDetailModel.solar_water_heater ? .tank : .inverter)
        editVC.index = index
        self.navigationController?.pushViewController(editVC, animated: false)
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: false)
    }
}
extension JobDetailInvertersListViewController: UITableViewDelegate{
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let panelModel = JobDetailModelHelper.shared.jobDetailModel.pvd_inverter_serial_numbers[indexPath.row]
        //show image
        if panelModel.image != ""{
            let imagesList: [BrowseImageData] = JobDetailModelHelper.shared.jobDetailModel.pvd_inverter_serial_numbers.filter({$0.image != ""}).map({BrowseImageData(image: $0.image, code: $0.code, codeType: .Panel)})
            let realIndex = imagesList.firstIndex(where: {$0.image == panelModel.image}) ?? 0
            if imagesList.count > 0 {
                let vc = BrowseImageViewController()
                vc.imagesArray = imagesList
                vc.currentIndex = realIndex
                self.navigationController?.pushViewController(vc,animated: true)
            }
        }

    }
    func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        if (JobDetailModelHelper.shared.jobDetailModel.solar_water_heater && JobDetailModelHelper.shared.jobDetailModel.canEditJobDetailFlag) || (!JobDetailModelHelper.shared.jobDetailModel.solar_water_heater && JobDetailModelHelper.shared.jobDetailModel.canEditJobDetailFlag){
            //edit
            let edit = UIContextualAction(style: .normal, title: nil) { action, view, completionHandler in
                //                var barcode:String!
                self.editInverterNumber(indexPath.row)
                completionHandler(true)
            }
            edit.image = R.image.list_cell_edit_icon()
            edit.backgroundColor = UIColor(hexStr: "#D9D9D9")
            //delete
            let delete = UIContextualAction(style: .normal, title: nil) { action, view, completionHandler in
                self.delOperation(indexPath.row)
                completionHandler(true)
            }
            delete.image = R.image.list_cell_delete_icon()
            delete.backgroundColor = UIColor(hexStr: "#ED3E3E")
            //返回所有的事件按钮
            let configuration = UISwipeActionsConfiguration(actions: [delete, edit])
            return configuration
        }
        return nil

    }
    //Custom Buttons when swipe cell left
    private func delOperation(_ index: Int) {
        let paneModel = JobDetailModelHelper.shared.jobDetailModel.pvd_inverter_serial_numbers[index]
        let barcode: String  = paneModel.code
        Tool().showAlertViewWithTwoBtns(title: barcode, message: R.string.localizable.areYouSureToDeleteThisSerialNumber(JobDetailModelHelper.shared.jobDetailModel.solar_water_heater ? "tank" : "inverter" ),noClosure: nil) {
            JobDetailModelHelper.shared.jobDetailModel.localDeletedInverterNumbers.append(paneModel)
            if paneModel.operType == "" {//空标识是server数据
                paneModel.removed = 1
                paneModel.pvd_id = JobDetailModelHelper.shared.jobDetailModel.id
                paneModel.operType = DataOperType.Del.rawValue
                //数据库增加删除的本地数据
                DBManager.shared.delSerialNumberData(model: paneModel,tableName: inverternumber_table_name)
                
                //有网络才能请求删除删除
                if Connectivity.isConnectedToInternet {
                    ModelViewUtil.shared.showLoadingView("Deleting...")
                    UploadManager.shared.uploadOneInverterNumber(paneModel){(succesFlag, code) in
                        ModelViewUtil.shared.hideLoadingView()
                    }
                }
            }else{//local data: 新增或修改
                DBManager.shared.deleteLocalPanelInverterByCode(tableName: inverternumber_table_name, code: paneModel.code)
            }
            //1.此代码放在操作数据库后边，因为broadCast时，有地方（flush upload）会用到本地数据的统计
            JobDetailModelHelper.shared.jobDetailModel.pvd_inverter_serial_numbers.remove(at: index)
            JobDetailModelHelper.shared.jobDetailModel.broadCastInverterData()
        }
    }
    
}
